package com.readpost.controller;

import com.github.pagehelper.PageInfo;
import com.readpost.doman.PageBean;
import com.readpost.doman.Dto.DraftArticleDto;
import com.readpost.doman.Entity.Articles;
import com.readpost.doman.Result;
import com.readpost.service.ArticlesService;
import com.readpost.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticlesService articlesService;

    @GetMapping("/list")
    public Result<String> list() {
      return Result.success("文章列表");
    }


    /**
     * 保存文章草稿
     * @param articles 文章信息
     * @return 创建结果
     */
    @PostMapping("/createArticle")
    public Result<String> createArticle(@Validated @RequestBody DraftArticleDto articles) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userid = (Integer) map.get("userid");
        articlesService.createArticle(articles ,userid);
        return Result.success("成功");
    }

    /**
     * 打开已保存草稿
     * @return 文章信息
     */
    @GetMapping("/contentDraftArticle")
    public Result<Articles> contentDraftArticle() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userid = (Integer) map.get("userid");
        Articles articles = articlesService.contentDraftArticle(userid);
        return Result.success(articles);
    }

    /**
     * 发布文章
     * @return 文章信息
     */
    @PostMapping("/publishArticle")
    public Result<String> publishArticle(@Validated @RequestBody DraftArticleDto articles) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userid = (Integer) map.get("userid");
        articlesService.publishArticle(articles,userid);
        return Result.success("成功");
    }


    @GetMapping
    public Result<PageInfo<Articles>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String state) {
        PageInfo<Articles> pb= articlesService.list(pageNum, pageSize, categoryId, state);
        return Result.success(pb);
    }
}
